<template>
  <div class="container">

  </div>
</template>

<script>
  import * as d3 from 'd3'

  export default {
    name: 'HelloWorld',
    data() {
      return {
        width: 800,
        height: 500,
        links: [{"source": " ", "target": " ", "value": 1}],
        nodes: [],
        linkName: [],
        nodeName: [],
        simulation: null,
        lastClickNode: "",
        svgArea: null,
        consecutiveClick: false,
        colorList: ['red', 'yellow', '#123501', '#223344', 'yellow', 'black', '#002266',
          '#ffee11', '#aebc23', 'red', 'blue', '#123501', '#223344',
          'yellow', 'black', '#002266', '#ffee11', '#aebc23'],
        testGraph: {
          "links": [],
          "nodes": [],
        }
      }
    },
    created() {
      const _this = this;
      this.axios.get("http://localhost:8081/api/Map/感冒")
        // this.axios.get("http://localhost:8081/api/Map/all")
        .then(function (response) {
          _this.testGraph["nodes"] = response.data
          _this.init(_this.testGraph)
        })
        .catch(function (response) {
          console.log(response)
        })

    },
    methods: {
      init(data) {
        const _this = this;
        const links = data.links;
        const nodes = data.nodes;
        _this.simulation = d3.forceSimulation(nodes)
          .force("link", d3.forceLink(links).id(d => d.id).distance(200))
          .force("charge", d3.forceManyBody().strength(-30))
          .force("center", d3.forceCenter(_this.width / 2, _this.height / 2));

        _this.svgArea = d3.select(".container")
          .append("svg")
          .attr("viewBox", [0, 0, _this.width, _this.height])
          .call(d3.zoom().on("zoom", function () {
            g.attr("transform", d3.event.transform)
          }))
        const g = _this.svgArea.append("g")
          .attr("class", "content")

        _this.links = g.append("g")
          .attr("stroke", "#999")
          .attr("stroke-opacity", 0.6)
          .selectAll("path")
          .data(links)
          .join("path")
          .attr("marker-end", "url(#positiveMarker)")
          .attr("stroke-width", d => Math.sqrt(d.value))
          .attr("class", "link")
          .attr("id", d => d.source + "_" + d.relationship + "_" + d.target)

        _this.nodes = g.append("g")
          .selectAll("circle")
          .data(nodes, d => d.id)
          .join("circle")
          .attr("r", 30)
          .attr("fill", this.color)
          .call(this.drag(_this.simulation))
          .classed("node", true)
          .on("click", this.nodeClick)
          .attr("id", d => d.id)

        _this.nodes.append("title")
          .text(d => d.id);

        _this.nodeName = g.append("g")
          .selectAll("text")
          .data(nodes)
          .join("text")
          .attr("class", "nodeName")
          .text(d => d.id)
          .attr("fill", "white")
          .attr("dy", 50)
          .attr("dx", function () {
            return this.getBoundingClientRect().width / 2 * (-1)
          })

        _this.linkName = g.append("g")
          .selectAll("path")
          .data(links)
          .join("path")
          .attr('startOffset', '50%')
          .style('text-anchor', 'middle')
          .style('fill', 'black')
          .style('font-size', '10px')
          .style('font-weight', 'bold')
          .append("textPath")
          .attr(
            'xlink:href', d => "#" + d.source + "_" + d.relationship + "_" + d.target
          )
          .text(function (d) {
            return d.relationship;
          });

        _this.simulation.on("tick", () => {
          _this.links
            .attr("d", function (d) {
              if (d.source.x < d.target.x) {
                return "M " + d.source.x + " " + d.source.y + " L " + d.target.x + " " + d.target.y
              } else {
                return "M " + d.target.x + " " + d.target.y + " L " + d.source.x + " " + d.source.y
              }
            })
            .attr("marker-end", function (d) {
              if (d.source.x < d.target.x) {
                return "url(#positiveMarker)"
              } else {
                return null
              }
            })
            .attr("marker-start", function (d) {
              if (d.source.x < d.target.x) {
                return null
              } else {
                return "url(#negativeMarker)"
              }
            })
          _this.nodes
            .attr("cx", d => d.x)
            .attr("cy", d => d.y);

          _this.nodeName
            .attr("x", d => d.x)
            .attr("y", d => d.y)
        });
        this.addMarkers();
      },
      color(d) {
        return this.colorList[d.group]
      },
      drag(simulation) {
        function dragstarted(d) {
          if (!d3.event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
        }

        function dragged(d) {
          d.fx = d3.event.x;
          d.fy = d3.event.y;
        }

        function dragended(d) {
          if (!d3.event.active) simulation.alphaTarget(0.5);
          d.fx = null
          d.fy = null
        }

        return d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended);
      },
      nodeClick(d) {
        const _this = this;
        if (_this.lastClickNode == d.id && _this.consecutiveClick) {
          _this.consecutiveClick = !_this.consecutiveClick;
          this.axios.get("http://localhost:8081/api/Map/" + d.id)
            // this.axios.get("http://localhost:8081/api/Map/all")
            .then(function (response) {
              //TODO  待完善
              d3.select('svg').remove()
              _this.testGraph["nodes"] = response.data
              _this.testGraph["links"] = []
              _this.links = []
              _this.nodes = []
              _this.init(_this.testGraph)
            })
            .catch(function (response) {
              console.log(response)
            })
        } else {
          _this.consecutiveClick = !_this.consecutiveClick;
          _this.lastClickNode = d.id;
          this.axios.get("http://localhost:8081/api/Map/leadedby/" + d.id)
            .then(function (response) {
              for (let i = 0; i < response.data.length; i++) {
                let flag = true;
                for (let j = 0; j < _this.testGraph.nodes.length; j++) {
                  if (_this.testGraph.nodes[j].id === response.data[i].id) {
                    flag = false;
                    break;
                  }
                }
                if (flag) {
                  _this.testGraph.nodes.push(response.data[i])
                  _this.testGraph.links.push({
                    "source": d.id,
                    "target": response.data[i].id,
                    "value": 5,
                    "relationship": "SHOWED"
                  })
                }
              }
              console.log(_this.testGraph)
              _this.updateGraph(_this.testGraph)
            })
            .catch(function (response) {
              console.log(response)
            })
        }

      },
      updateGraph(data) {
        const _this = this;
        const links = data.links;
        const nodes = data.nodes;

        _this.links = _this.links
          .data(links, (d) => {
            return d.source.id + "-" + d.target.id;
          })
          .enter()
          .append("path")
          .attr("stroke", "#999")
          .attr("stroke-opacity", 0.6)
          .attr("stroke-width", d => Math.sqrt(d.value))
          .attr("marker-end", "url(#positiveMarker)")
          .merge(_this.links)
          .attr("class", "link")
          .attr("id", d => d.source + "_" + d.relationship + "_" + d.target)

        _this.nodes = _this.nodes
          .data(nodes)
          .enter()
          .append("circle")
          .attr("r", 30)
          .attr("class", "node")
          .attr("fill", this.color)
          .merge(_this.nodes)
          .on("click", this.nodeClick)
          .call(_this.drag(_this.simulation))
          .attr("id", d => d.id)
        _this.nodes.append("title")
          .text(d => d.id);
        _this.nodeName = _this.nodeName
          .data(nodes)
          .join("text")
          .attr("class", "nodeName")
          .text(d => d.id)
          .attr("fill", "white")
          .attr("dy", 50)
          .attr("dx", function () {
            return this.getBoundingClientRect().width / 2 * (-1)
          })

        _this.linkName = _this.linkName
          .data(links)
          .enter()
          .append('text')
          .style('text-anchor', 'middle')
          .style('fill', 'white')
          .style('font-size', '10px')
          .style('font-weight', 'bold')
          .append('textPath')
          .attr(
            'xlink:href', d => "#" + d.source + "_" + d.relationship + "_" + d.target
          )
          .attr('startOffset', '50%')
          .merge(_this.linkName)
          .text(function (d) {
            return d.relationship;
          })

        _this.simulation.nodes(nodes)
        _this.simulation.force("link").links(links)
        _this.simulation.alpha(0.2).restart()
      },
      addMarkers() {
        const positiveMarker = this.svgArea.append("marker")
          .attr("id", "positiveMarker")
          .attr("orient", "auto")
          .attr("stroke-width", 2)
          .attr("markerUnits", "strokeWidth")
          .attr("markerUnits", "userSpaceOnUse")
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", 35)
          .attr("refY", 0)
          .attr("markerWidth", 12)
          .attr("markerHeight", 12)
          .append("path")
          .attr("d", "M 0 -5 L 10 0 L 0 5")
          .attr('fill', '#999')
          .attr("stroke-opacity", 0.6);
        const negativeMarker = this.svgArea.append("marker")
          .attr("id", "negativeMarker")
          .attr("orient", "auto")
          .attr("stroke-width", 2)
          .attr("markerUnits", "strokeWidth")
          .attr("markerUnits", "userSpaceOnUse")
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", -25)
          .attr("refY", 0)
          .attr("markerWidth", 12)
          .attr("markerHeight", 12)
          .append("path")
          .attr("d", "M 10 -5 L 0 0 L 10 5")
          .attr('fill', '#999')
          .attr("stroke-opacity", 0.6);
      },
    }
  }
</script>


<style>
  body {
    margin: 0px;
  }

  .container {
    width: 800px;
    height: 500px;
    border: 1px solid #2c3e50;
    border-radius: 8px;
    margin-top: 40px;
    margin-left: auto;
    margin-right: auto;
    background: #154360 repeating-linear-gradient(30deg,
    hsla(0, 0%, 100%, .1), hsla(0, 0%, 100%, .1) 15px,
    transparent 0, transparent 30px);
  }

  .node {
    stroke: #fff;
    stroke-width: 1;
    cursor: pointer;
  }

  .node:hover {
    stroke-width: 5;
  }

  .nodeName {
    fill: white;
  }
</style>
